//
//  LoaginViewController.m
//  B项目
//
//  Created by lanou on 16/8/6.
//  Copyright © 2016年 Work. All rights reserved.
//

#import "LoaginViewController.h"
#import "PrefixHeader.pch"
#import "RegistViewController.h"
#import "forgotViewController.h"
#import "MyViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "MBProgressHUD.h"


@interface LoaginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)UIImageView *pictureImg;
//用户名
@property(nonatomic,strong)UITextField *userTF;

//密码
@property(nonatomic,strong)UITextField *passWordUserTF;
@property(nonatomic,strong)MBProgressHUD *HUD;
@end

@implementation LoaginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.navigationItem.title = @"登陆";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemAction)];
    self.navigationItem.leftBarButtonItem = leftItem;

    [self setLoagin];
    
}


//返回事件
- (void)leftItemAction
{
    [self.navigationController popViewControllerAnimated:YES];

}



- (void)setLoagin
{

    UIView *userView = [[UIView alloc]initWithFrame:CGRectMake(20, 30, kScreenWidth - 40, 60)];

    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineView.backgroundColor = [UIColor grayColor];
     UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];

    userImg.image = [UIImage imageNamed:@"login_username_icon@2x.png"];



    self.userTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, userView.ownWidth -40, 30)];
    _userTF.tag = 10;
    _userTF.delegate = self;
    _userTF.placeholder = @"手机号或者昵称";
    _userTF.font = [UIFont systemFontOfSize:14];
    [_userTF setBorderStyle:(UITextBorderStyleNone)];
    [userView addSubview:_userTF];
    [userView addSubview:userImg];
    [userView addSubview:lineView];
    [self.view addSubview:userView];


    UIView *passWordView = [[UIView alloc]initWithFrame:CGRectMake(20, 90, kScreenWidth - 40, 60)];

    UIView *lineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineViewP.backgroundColor = [UIColor grayColor];
    UIImageView *passWordImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];
    passWordImg.image = [UIImage imageNamed:@"login_password_icon@2x.png"];



    self.passWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, passWordView.ownWidth -120, 30)];
    _passWordUserTF.delegate = self;
    _passWordUserTF.placeholder = @"密码";
    _passWordUserTF.tag = 11;
    _passWordUserTF.font = [UIFont systemFontOfSize:14];
    [_passWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(passWordImg.ownWidth + _passWordUserTF.ownWidth, 10, 100, 30)];
    img.userInteractionEnabled = YES;
    img.image = [UIImage imageNamed:@"login_forgot_button@2x.png"];
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    button.frame = CGRectMake(10, 0, 80, 30);
    [button setTitle:@"忘记密码" forState:(UIControlStateNormal)];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [img addSubview:button];
   
    [button addTarget:self action:@selector(fogetWordAction) forControlEvents:(UIControlEventTouchUpInside)];
    [passWordView addSubview:lineViewP];
    [passWordView addSubview:_passWordUserTF];
    [passWordView addSubview:passWordImg];
    [passWordView addSubview:img];
    [self.view addSubview:passWordView];

    UIImageView *LoaginImg = [[UIImageView alloc]initWithFrame:CGRectMake(20, 180, kScreenWidth - 40, 30)];
    LoaginImg.userInteractionEnabled = YES;
    LoaginImg.image = [UIImage imageNamed:@"login_tip_button@2x.png"];
    UIButton *LoaginBT = [[UIButton alloc]initWithFrame:CGRectMake((LoaginImg.ownWidth -60)/2, 0, 60, 30)];
    [LoaginBT setTitle:@"登陆" forState:(UIControlStateNormal)];
    [LoaginBT setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [LoaginBT addTarget:self action:@selector(loaginBTAction) forControlEvents:(UIControlEventTouchUpInside)];
    [LoaginImg addSubview:LoaginBT];
    [self.view addSubview:LoaginImg];

    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth -80)/2, kScreenHeight -100, 80, 30)];
    lable.text = @"没有账号？";
    lable.font = [UIFont systemFontOfSize:12];

    [self.view addSubview:lable];


    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth -105), kScreenHeight -100, 100, 30)];
    imgView.image = [UIImage imageNamed:@"login_forgot_button@2x.png"];
    imgView.userInteractionEnabled = YES;
    UIButton *registBT = [UIButton buttonWithType:(UIButtonTypeCustom)];
    registBT.frame = CGRectMake(10, 0, 80, 30);
    [registBT setTitle:@"快速注册" forState:(UIControlStateNormal)];
    [registBT setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    registBT.titleLabel.font = [UIFont systemFontOfSize:12];
    [registBT addTarget:self action:@selector(rgistAction) forControlEvents:(UIControlEventTouchUpInside)];
     [imgView addSubview:registBT];
    [self.view addSubview:imgView];


}

//忘记密码点击事件
- (void)fogetWordAction
{
    forgotViewController *forgotVC = [[forgotViewController alloc]init];
    [self.navigationController pushViewController:forgotVC animated:YES];
  
}


//登陆
- (void)loaginBTAction
{
    if ([_userTF.text isEqualToString:@""]||[_passWordUserTF.text isEqualToString:@""]) {
        [self showAlert:@"用户名和密码不能为空"];
    }else{
        if (_userTF.text.length == 11) {

            [AVUser logInWithMobilePhoneNumberInBackground:_userTF.text password:_passWordUserTF.text block:^(AVUser *user, NSError *error) {
                if (user != nil) {
                    UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"恭喜" message:@"登陆成功" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *alerAction = [UIAlertAction actionWithTitle:@"好的" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

//                        //获取图片路径
//                        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//                        NSString *documentDirectory = [paths objectAtIndex:0];
//
//                        NSString *imagePath = [documentDirectory stringByAppendingString:@"/image.png"];
//
//                        //block传值
//                        //self.str_block (self.userTF.text,self.urlString);
////                        self.str_block(self.userTF.text,imagePath);
                        [self.navigationController popViewControllerAnimated:YES];

                    }];

                    [self presentViewController:alerC animated:YES completion:nil];

                    [alerC addAction:alerAction];
                    self.HUD = [[MBProgressHUD alloc]init];
                    [self.view addSubview:self.HUD];
                    self.HUD.dimBackground = YES;

                    _HUD.mode = MBProgressHUDModeIndeterminate;
                    _HUD.opacity = 0.5;
                    //    _HUD.color = [UIColor clearColor];
                    _HUD.color = [_HUD.color colorWithAlphaComponent:1];
                    _HUD.labelFont = [UIFont systemFontOfSize:13];
                    self.HUD.labelText = @"loading...";
                    _HUD.minShowTime = 1.5;
                    _HUD.cornerRadius = 20;
                    _HUD.activityIndicatorColor = [UIColor redColor];
                    _HUD.animationType = MBProgressHUDAnimationZoomIn;
                    [_HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
                }else{
                    UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"登陆失败" message:@"用户名或密码错误" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *alerAction = [UIAlertAction actionWithTitle:@"请重新核对后输入" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

                    }];

                    [self presentViewController:alerC animated:YES completion:nil];
                    [alerC addAction:alerAction];
                }
                
            }];
        }else{
                    [AVUser logInWithUsernameInBackground:_userTF.text password:_passWordUserTF.text block:^(AVUser *user, NSError *error) {
                        if (user != nil) {
            
                        UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"恭喜" message:@"登陆成功" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *alerAction = [UIAlertAction actionWithTitle:@"好的" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

                        [self.navigationController popViewControllerAnimated:YES];
            
                        }];
            
                      [self presentViewController:alerC animated:YES completion:nil];
            
                      [alerC addAction:alerAction];
                            self.HUD = [[MBProgressHUD alloc]init];
                            [self.view addSubview:self.HUD];
                            self.HUD.dimBackground = YES;
            
                            _HUD.mode = MBProgressHUDModeIndeterminate;
                            _HUD.opacity = 0.5;
                            //    _HUD.color = [UIColor clearColor];
                            _HUD.color = [_HUD.color colorWithAlphaComponent:1];
                            _HUD.labelFont = [UIFont systemFontOfSize:13];
                            self.HUD.labelText = @"loading...";
                            _HUD.minShowTime = 1.5;
                            _HUD.cornerRadius = 20;
                            _HUD.activityIndicatorColor = [UIColor redColor];
                            _HUD.animationType = MBProgressHUDAnimationZoomIn;
                            [_HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
            
            
                        } else {
                            UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"登陆失败" message:@"用户名或密码错误" preferredStyle:(UIAlertControllerStyleAlert)];
                            UIAlertAction *alerAction = [UIAlertAction actionWithTitle:@"请重新核对后输入" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
                            }];
            
                            [self presentViewController:alerC animated:YES completion:nil];
                            [alerC addAction:alerAction];
            
            
                    }
                }];

        }

    }

}


//任务，测试进度显示
- (void)myProgressTask {
    // This just increases the progress indicator in a loop
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        _HUD.progress = progress;
        usleep(50000);
    }
}


//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    if (textField.tag != 11) {
        [[self.view viewWithTag:11]becomeFirstResponder];

    }else{
        [[self.view viewWithTag:11]resignFirstResponder];
    }


    return YES;
}


//注册
- (void)rgistAction
{
    RegistViewController *registVC = [[RegistViewController alloc]init];


    [self.navigationController pushViewController:registVC animated:YES];
    

}

//点击事件的提示框
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}


- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];

    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}

////判断输入格式
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    NSMutableString *currentPassWordStr = [NSMutableString stringWithString:_userTF.text];
//    [currentPassWordStr replaceCharactersInRange:range withString:string];
//    [YGValidator validateText:currentPassWordStr regular:@"\\w{6,16}"@"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$" textField:_userTF correctImage:@"true" errorImage:@"error"];
//
//    return YES;
//
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
